//
//  LBCHomeViewController.m
//  LifeEnjoy
//
//  Created by 刘表聪 on 15/9/9.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "LBCHomeViewController.h"
#import "LBCWebViewController.h"
#import "LBCFirstSectionCell.h"
#import "LBCSecondSectionCell.h"
#import "LBCBTView.h"

// 工具
#import "LBCTopDataTool.h"

// 第三方
#import "SDCycleScrollView.h"
#import "AFNetworking.h"

// 模型
#import "LBCTopNews.h"
#import "LBCHomeGoods.h"


#define kButtonWidth ((kScreenWidth - 120) / 4)

typedef NS_ENUM(NSUInteger, TopButtonType) {
    TopButtonTypeCollecton = 90,
    TopButtonTypeVideo,
    TopButtonTypeEssence,
    TopButtonTypeMeme
};

@interface LBCHomeViewController () <UITableViewDataSource, UITableViewDelegate, SDCycleScrollViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *homeTableView;

// 头部视图
@property (nonatomic, strong) UIView *topView;
// 轮播图
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;
// LBCBTView 数组
@property (nonatomic, strong) NSMutableArray *BTViewArray;

// FirstGoodsArray
@property (nonatomic, strong) NSMutableArray *firstGoodsArray;

// SecondGoodsArray
@property (nonatomic, strong) NSMutableArray *secondGoodsArray;


@end

@implementation LBCHomeViewController


static NSString *firstCellIdentifier = @"firstCellIdentifier";
static NSString *secondCellIdentifier = @"secondCellIdentifier";

#pragma mark - 懒加载
- (NSMutableArray *)BTViewArray
{
    if (!_BTViewArray) {
        self.BTViewArray = [NSMutableArray array];
    }
    return _BTViewArray;
}

- (NSMutableArray *)firstGoodsArray
{
    if (!_firstGoodsArray) {
        self.firstGoodsArray = [NSMutableArray array];
    }
    return _firstGoodsArray;
}

- (NSMutableArray *)secondGoodsArray
{
    if (!_secondGoodsArray) {
        self.secondGoodsArray = [NSMutableArray array];
    }
    return _secondGoodsArray;
}

#pragma mark viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 注册
    [self.homeTableView registerNib:[UINib nibWithNibName:@"LBCFirstSectionCell" bundle:nil] forCellReuseIdentifier:firstCellIdentifier];
     [self.homeTableView registerNib:[UINib nibWithNibName:@"LBCSecondSectionCell" bundle:nil] forCellReuseIdentifier:secondCellIdentifier];
    
  
    // 创建头部View
    self.homeTableView.tableHeaderView = [self createTopView];
    
    [LBCTopDataTool sharedLBCTopDataTool].updateTopBlock = ^() {
        // 设置轮播图
        _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
        self.cycleScrollView.imageURLStringsGroup = [LBCTopDataTool sharedLBCTopDataTool].scrollImageUrls;
        // 设置Button
        for (int i = 0; i < _BTViewArray.count; i++) {
            LBCBTView *BTView = _BTViewArray[i];
            LBCTopNews *topNews = [[LBCTopDataTool sharedLBCTopDataTool] topNewsAtIndex:i];
            [BTView setValuesWithImageUrlStr:topNews.imgUrl title:topNews.title];
        }
    };
    
    // 加载数据
    [self loadData];
    
    
}

#pragma mark - 加载数据
- (void)loadData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", nil];
    [manager GET:kHomeListUrl(1) parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        for (NSDictionary *dict in responseObject[@"blast_items"]) {
            LBCHomeGoods *homeGoods = [LBCHomeGoods new];
            [homeGoods setValuesForKeysWithDictionary:dict];
            [self.firstGoodsArray addObject:homeGoods];
        }
        
        for (NSDictionary *dict in responseObject[@"tuan_items"]) {
            LBCHomeGoods *homeGoods = [LBCHomeGoods new];
            [homeGoods setValuesForKeysWithDictionary:dict];
            [self.secondGoodsArray addObject:homeGoods];
        }
        
        [self.homeTableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.firstGoodsArray.count;
    }
    return self.secondGoodsArray.count / 2;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        LBCFirstSectionCell *cell = [tableView dequeueReusableCellWithIdentifier:firstCellIdentifier forIndexPath:indexPath];
        [cell setValuesWithGoodsModel:self.firstGoodsArray[indexPath.row]];
        
        // 选中的属性
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    LBCSecondSectionCell *cell = [tableView dequeueReusableCellWithIdentifier:secondCellIdentifier forIndexPath:indexPath];
    [cell setValuesWithLeftGoodsModel:self.secondGoodsArray[indexPath.row * 2] rightGoodsModel:self.secondGoodsArray[indexPath.row * 2 + 1] indexRow:indexPath.row];
    return cell;
  
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    // 顶部视图
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    view.backgroundColor = [UIColor whiteColor];
    // 隔离灰色视图
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
    grayView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:grayView];
    // 红色视图
    UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(5, 15, 3, 20)];
    redView.backgroundColor = [UIColor redColor];
    [view addSubview:redView];
    // 线条视图
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 39, kScreenWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    // 文字Label
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, 100, 20)];
    [view addSubview:lable];
    if (section == 0) {
        lable.text = @"爆款推荐";
    } else {
        lable.text = @"每天9点上新";
    }
    
    return view;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        return 140;
    }
    return (kScreenWidth - 30) * 0.5  + 50;
    
}


#pragma mark - 创建顶部视图
- (UIView *)createTopView
{
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight * 0.4)];
    _topView.backgroundColor = [UIColor whiteColor];
    

    NSArray *array = @[[UIImage imageNamed:@"placeholder.png"]];
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, _topView.frame.size.height * 0.7) imagesGroup:array];
    _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolStyleNone;
    _cycleScrollView.autoScroll = YES;
    _cycleScrollView.autoScrollTimeInterval = 3;
    _cycleScrollView.dotColor = [UIColor pinkColor];
    _cycleScrollView.placeholderImage = [UIImage imageNamed:@"placeholder.png"];
    _cycleScrollView.delegate = self;
    [_topView addSubview:_cycleScrollView];
    
    // 设置LBCBTView
    for (int i = 0; i < 4; i++) {
        LBCBTView *BTView = [[LBCBTView alloc] initWithFrame:CGRectMake(10 + 33 * i  + kButtonWidth * i, _cycleScrollView.frame.size.height + 5, kButtonWidth, _topView.frame.size.height * 0.3 - 5)];
        // 添加按钮事件
        [BTView.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        BTView.button.tag = 90 + i;
        [_topView addSubview:BTView];
        [self.BTViewArray addObject:BTView];
    }
    
    
    return _topView;
}

#pragma mark - 绑定按钮事件
- (void)buttonAction:(UIButton *)sender
{
    switch (sender.tag) {
        case TopButtonTypeCollecton: {
            break;
        }
        case TopButtonTypeVideo: {
            LBCTopNews *topNews = [[LBCTopDataTool sharedLBCTopDataTool] topNewsAtIndex:1];
            NSString *htmlStr = [topNews.toUrl componentsSeparatedByString:@"|"].lastObject;
            LBCWebViewController *webVC = [[LBCWebViewController alloc] init];
            webVC.htmlStr = htmlStr;
            webVC.hidesBottomBarWhenPushed=YES;

            [self.navigationController showViewController:webVC sender:nil];
            break;
        }
        case TopButtonTypeEssence: {
//            LBCTopNews *topNews = [[LBCTopDataTool sharedLBCTopDataTool] topNewsAtIndex:2];
//            NSString *htmlStr = [topNews.toUrl componentsSeparatedByString:@"|"].lastObject;
//            LBCWebViewController *webVC = [[LBCWebViewController alloc] init];
//            webVC.htmlStr = htmlStr;
//            [self.navigationController showViewController:webVC sender:nil];
            break;
        }
        case TopButtonTypeMeme: {
            LBCTopNews *topNews = [[LBCTopDataTool sharedLBCTopDataTool] topNewsAtIndex:3];
            NSString *htmlStr = [topNews.toUrl componentsSeparatedByString:@"|"].lastObject;
            LBCWebViewController *webVC = [[LBCWebViewController alloc] init];
            webVC.htmlStr = htmlStr;
            webVC.hidesBottomBarWhenPushed=YES;

            [self.navigationController showViewController:webVC sender:nil];
            break;
        }
            
        default:
            break;
    }
}

#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    if ([LBCTopDataTool sharedLBCTopDataTool].scrollImageUrls.count > 0) {
        LBCTopNews *topNews = [[LBCTopDataTool sharedLBCTopDataTool] topImageNewsAtIndex:index];
        NSString *htmlStr = [topNews.toUrl componentsSeparatedByString:@"|"].lastObject;
        LBCWebViewController *webVC = [[LBCWebViewController alloc] init];
        webVC.htmlStr = htmlStr;
        // Push 之前隐藏tabBar
        webVC.hidesBottomBarWhenPushed=YES;
        [self.navigationController showViewController:webVC sender:nil];
    }
   
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
